/*
 * Copyright (C) 2016 Lokiy(liulongke@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  　　　　http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.lokiy.kit.ktx

import android.os.Looper
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.NotifyWhenChangedValueLiveData

/**
 * LiveDatas
 * @author Lokiy
 * 2021-04-27 10:27
 */

fun <T> mutableLiveDataOf(t: T? = null) = if (t == null) MutableLiveData<T>() else MutableLiveData<T>(t)

fun <T> T?.asLiveData(): MutableLiveData<T> = if (this == null) MutableLiveData() else MutableLiveData(this)

/**
 * 合并liveData数据
 */
fun <A, B, C> LiveData<A>.combiner(that: LiveData<B>, block: (A, B) -> C): LiveData<C> {
    val liveData = MediatorLiveData<C>()
    var a: A? = null
    var b: B? = null
    val test = @Synchronized
    {
        val a1 = a
        val b1 = b
        if (a1 != null && b1 != null) {
            liveData.postValue(block.invoke(a1, b1))
        }
    }
    liveData.addSource(this) {
        a = it
        test.invoke()
    }
    liveData.addSource(that) {
        b = it
        test.invoke()
    }
    return liveData
}

fun <T> LiveData<T>.notifyChanged(t: T? = null) {
    if (this is MutableLiveData<T>) {
        val value: T? = t ?: this.value
        if (Looper.myLooper() == Looper.getMainLooper()) {
            this.value = value
        } else {
            this.postValue(value)
        }
    }
}

/**
 * 值有变化的时候才会通知
 */
fun <X, Y> LiveData<X>.mapNotifyWhenChanged(transform: (X) -> Y): LiveData<Y> {
    val liveData = NotifyWhenChangedValueLiveData<Y>()
    liveData.addSource(this) { x -> liveData.setValue(transform.invoke(x)) }
    return liveData
}